from sqlalchemy import desc
from src.common.logger import getLogger

logger = getLogger()

def load_history_records(args):
    from ..model.history_record import HistoryRecord
    source = args.get("source")
    pattern = args.get("pattern")

    query = HistoryRecord.query

    if source:
        query = query.filter(HistoryRecord.source == source)
    if pattern:
        query = query.filter(HistoryRecord.pattern == pattern)

    records = query.order_by(desc(HistoryRecord.create_time)).all()

    list = []
    for record in records:
        item = record.to_dict()
        if item["create_time"]:
            item["create_time"] = item["create_time"].strftime('%Y-%m-%d %H:%M:%S')
        list.append(item)
    return list

def select_history_record(args):
    from ..model.history_record import HistoryRecord
    id = args.get("source_id")
    record = HistoryRecord.query.filter(HistoryRecord.id == id).first()
    return record

def insert_history_record(history_record):
    from ... import db
    db.session.add(history_record)
    db.session.commit()

def update_history_record(args):
    from ... import db
    from ..model.history_record import HistoryRecord

    old_record = HistoryRecord.query.get(args.get("id"))
    old_record.name = args.get("name")
    db.session.commit()

def delete_history_record(id):
    from ... import db
    from ..model.history_record import HistoryRecord

    record = HistoryRecord.query.get(id)
    db.session.delete(record)
    db.session.commit()
